package com.doujiao.auth.config;

import com.doujiao.auth.utils.JwtUtil;

import com.doujiao.core.exceptions.BusinessException;

import com.doujiao.auth.service.AdminService;
import com.doujiao.core.exceptions.enums.RespEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;
import java.util.List;

@Component
public class PermissionInterceptor implements HandlerInterceptor {

    private final AdminService adminService;
    private final JwtUtil jwtUtil;

    public PermissionInterceptor(AdminService adminService, JwtUtil jwtUtil) {
        this.adminService = adminService;
        this.jwtUtil = jwtUtil;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是Controller方法直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        // 检查是否需要权限验证
        if (method.isAnnotationPresent(RequiresPermission.class)) {
            RequiresPermission annotation = method.getAnnotation(RequiresPermission.class);
            String requiredPermission = annotation.value();

            // 从token中获取用户ID
            String token = request.getHeader("Authorization");
            Long adminId = jwtUtil.getAdminId(token);

            // 查询用户权限
            List<String> permissions = adminService.getAdminPermissions(adminId);

            // 验证权限
            if (!permissions.contains(requiredPermission)) {
                throw new BusinessException(RespEnum.PERMISSION_DENIED);
            }
        }

        return true;
    }
}
